package cn.msi.question.service;

import java.util.List;

import cn.common.manager.SessionManager;
import cn.common.util.GeneralUtils;
import cn.msi.customer.domain.User;
import cn.msi.question.domain.Option;
import cn.msi.question.domain.Question;
import cn.msi.question.mapper.QuestionMapper;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * 样题业务处理类
 * 
 * @author Administrator
 * 
 */
public class QuestionService {

	private QuestionMapper questionMapper;

	/**
	 * 查询样题库
	 * 
	 * @param question
	 * @return
	 */
	public String searchQuestion(Question question) {
		return GeneralUtils.easyUI(questionMapper.count(question), questionMapper.selectList(question));
	}

	/**
	 * 查找样题
	 * 
	 * @param question
	 * @return
	 */
	public Question findQuestion(Question question) {
		if (question.getQuestionId() != null) {
			question = questionMapper.selectById(question.getQuestionId());
		}
		return question;
	}

	/**
	 * 保存样题
	 * 
	 * @param question
	 */
	public void modifyQuestion(Question question) {
		String text = question.getText();
		List<Option> options = null;
		if (text != null && !text.equals("")) {
			java.lang.reflect.Type type = new TypeToken<List<Option>>() {
			}.getType();
			Gson gson = new Gson();
			options = gson.fromJson("[" + text + "]", type);
		}
		// 保存样题
		if (question.getQuestionId() != null) {
			questionMapper.deleteByQuestionId(question.getQuestionId());
			questionMapper.update(question);
		} else {
			User user = (User) SessionManager.getAttr("user");
			question.setCustId(user.getCustId());
			questionMapper.insert(question);
		}
		// 保存选项
		if (question.getQuestionType().equals("R")) {
			addOptions(question.getQuestionId(), options);
		} else if (question.getQuestionType().equals("C")) {
			addOptions(question.getQuestionId(), options);
		}
	}

	/**
	 * 删除样题
	 * 
	 * @param question
	 */
	public void delQuestion(Question question) {
		questionMapper.deleteByQuestionId(question.getQuestionId());
		questionMapper.deleteById(question.getQuestionId());
	}

	/**
	 * 根据ids查询样题
	 * 
	 * @param ids
	 * @return
	 */
	public String searchQuestionByIds(String ids) {
		String[] id = ids.split(",");
		return GeneralUtils.easyUI(questionMapper.selectListBYids(id));
	}

	/**
	 * 保存选项题
	 * 
	 * @param question
	 */
	private void addOptions(Integer questionId, List<Option> options) {
		if (options != null) {
			for (Option o : options) {
				o.setQuestionId(questionId);
				questionMapper.insertOption(o);
			}
		}
	}

	public void setQuestionMapper(QuestionMapper questionMapper) {
		this.questionMapper = questionMapper;
	}

}
